package com.calligraphy.user.service.impl;

import com.calligraphy.bases.utils.AESUtil;
import com.calligraphy.bases.utils.ConcurrentHashMapCache;
import com.calligraphy.bases.utils.KeyUtil;
import com.calligraphy.user.service.MailService;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author hy
 * @Date 2018/12/27 10:39
 **/
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    private static final String templateName = "Message.ftl";

    @Value("${spring.mail.username}")
    public String from;

    @Value("${domain.name}")
    private String domainName;

    @Autowired
    private FreeMarkerConfigurer configurer;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    @Async
    public void sendMail(String title, String url, String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setSubject(title);
        message.setTo(email);
        message.setText(url);
        try{
            mailSender.send(message);
            log.info("【邮件已经发送出去】");
        } catch (Exception e) {
            log.error("【邮件没有发送出去】" + e);
        }
    }

    @Override
    @Async
    public void sendTemplateMail(Object message, String title, String email) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(InternetAddress.parse(email));
            helper.setSubject( title + " " + LocalDate.now() + " " + LocalTime.now().withNano(0));
            Map<String, Object> model = new HashMap<>(100);
            model.put("result", message);
            try {
                Template template = configurer.getConfiguration().getTemplate(templateName);
                try {
                    String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
                    helper.setText(text, true);
                    mailSender.send(mimeMessage);
                } catch (TemplateException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Async
    public void registerNotify(String email) {
        String key = AESUtil.encryptData(email);
        ConcurrentHashMapCache.put(key,email,ConcurrentHashMapCache.CACHE_HOLD_TIME_5M);
        String url = "http://" + domainName + "/user/verify?key=" + key;
        sendMail("calligraphy激活邮件",url,email);
    }

    @Override
    @Async
    public void resetPs(String email) {
        String randomKey = KeyUtil.random();
        ConcurrentHashMapCache.put(randomKey,email,ConcurrentHashMapCache.CACHE_HOLD_TIME_5M);
        String url = "http://" + domainName + "/user/reset?key=" + randomKey;
        sendMail("calligraphy密码重置邮件",url,email);
    }

}
